package com.santu.edu.supporter.config;

import cn.hutool.core.collection.CollUtil;
import com.santu.edu.supporter.interceptor.ReturnValueHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author luoyaoqi
 * @createTime 2024/2/23
 * @description
 */
@Configuration
public class ReturnValueHandlerConfig implements InitializingBean {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @Override
    public void afterPropertiesSet() {
        List<HandlerMethodReturnValueHandler> returnValueHandlerList = handlerAdapter.getReturnValueHandlers();
        if (CollUtil.isNotEmpty(returnValueHandlerList)) {
            List<HandlerMethodReturnValueHandler> newReturnValueHandlerList = new ArrayList<>(returnValueHandlerList.size());
            returnValueHandlerList.forEach(returnValueHandler -> {
                if (returnValueHandler instanceof RequestResponseBodyMethodProcessor) {
                    newReturnValueHandlerList.add(new ReturnValueHandler(returnValueHandler));
                } else {
                    newReturnValueHandlerList.add(returnValueHandler);
                }
            });
            handlerAdapter.setReturnValueHandlers(newReturnValueHandlerList);
        }
    }
}
